﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoupdateClient.Mgr
{
    internal class ClientMgr
    {
        #region Instance

        private static ClientMgr instance { set; get; } = null;

        public static ClientMgr getInstance()
        {
            if (instance == null)
            {
                instance = new ClientMgr();
            }

            return instance;
        }

        #endregion

        public Client.Client client { private set; get; } = null;

        public void ConnectToServer()
        {
            if (this.client == null)
            {
                this.client = new Client.Client();

                this.client.connectAsync(ConfigMgr.getInstance().config.serverAddress, ConfigMgr.getInstance().config.serverPort);
            }
        }



        public void registe()
        {
            if (this.client != null)
            {
                AutoUpdate.Model.Packet.Request.RegisteRequestPacket packet = new AutoUpdate.Model.Packet.Request.RegisteRequestPacket();

                packet.Topic = "Control".ToUpper();

                string msg = PacketMgr.getInstance().getPacketString(packet);

                new Task(new Action(() =>
                {
                    for (int i = 0; i < 3; i++)
                    {
                        System.Threading.Thread.Sleep(50);

                        ClientMgr.getInstance().client.sendMessage(msg);
                    }

                    DownloadMgr.getInstance().getNewestVersion();
                })).Start();
            }
        }

        public void heartbeat()
        {
            if (this.client != null)
            {
                AutoUpdate.Model.Packet.Request.HeartBeatRequestPacket packet = new AutoUpdate.Model.Packet.Request.HeartBeatRequestPacket();

                packet.Topic = "Control".ToUpper();

                string msg = PacketMgr.getInstance().getPacketString(packet);

                System.Threading.Thread.Sleep(100);

                ClientMgr.getInstance().client.sendMessage(msg);
            }
        }
    }
}
